package leetcode;

import entity.ListNode;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author 李栋
 * @version 1.0.0
 * @className Test160.java
 * @createTime 2021年06月04日 20:53:00
 */
public class Test160 {

    private static final Logger logger = LoggerFactory.getLogger(Test160.class);


    /**
     * 给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点，返回 null 。
     */

    @Test
    public void test() {
        ListNode l1 = new ListNode(1, new ListNode(3, new ListNode(5, new ListNode(7))));
        ListNode l2 = new ListNode(3, new ListNode(5, new ListNode(7)));
        ListNode intersectionNode = getIntersectionNode(l1, l2);
        ListNode intersectionNodeOne = getIntersectionNodeOne(l1, l2);
        logger.info(String.valueOf(intersectionNode));
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (Objects.isNull(headA) || Objects.isNull(headB)) {
            return null;
        }
        Set<ListNode> set = new HashSet<>();
        ListNode temp = headA;
        while (Objects.nonNull(temp)) {
            set.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (Objects.nonNull(temp)) {
            if (set.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }

    public ListNode getIntersectionNodeOne(ListNode headA, ListNode headB) {
        if (Objects.isNull(headA) || Objects.isNull(headB)) {
            return null;
        }
        ListNode l1 = headA;
        ListNode l2 = headB;
        while (l1 != l2) {
            l1 = Objects.isNull(l1) ? l2 : l1.next;
            l2 = Objects.isNull(l1) ? l1 : l2.next;
        }
        return l1;
    }

}
